<?php

namespace App\Admin\Forms\Aliyun;

use App\Enums\DomainSource;
use App\Enums\DomainType;
use App\Facades\AliyunDns;
use App\Models\Aliyun;
use App\Models\Application;
use App\Models\DomainPool;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Str;

class MiddleDomainForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * @param  array  $input
     * @return JsonResponse
     */
    public function handle(array $input): JsonResponse
    {
        if ($input['source'] == DomainSource::ALIYUN->value) {
            if (!Str::startsWith($input['rr'], '*.')) {
                $input['rr'] = '*.'.$input['rr'];
            }

            $domain = $input['rr'].'.'.$input['root'];
            if (DomainPool::where('domain', $domain)->exists()) {
                return $this->response()->error('域名必须全局唯一');
            }

            AliyunDns::aliyun(Aliyun::ofAdmin()->find($input['aliyun_id']))
                ->store($input['root'], $input['rr'], config('custom.slb_server_ip'));
        } else {
            if (!Str::startsWith($input['domain'], '*.')) {
                return $this->response()->error('域名必须以 "*." 开头');
            }

            $domain = $input['domain'];
            if (DomainPool::where('domain', $domain)->exists()) {
                return $this->response()->error('域名必须全局唯一');
            }
        }

        $data = [
            'source' => $input['source'],
            'type' => DomainType::STORAGE,
            'domain' => $domain,
            'rr' => $input['rr'],
            'root' => $input['root'],
            'status' => $input['status'],
            'ssl' => $input['ssl'],
        ];
        if (Admin::user()->isAdministrator()) {
            $data['application_id'] = $input['application_id'];
        }

        DomainPool::ofAdmin()->create($data);

        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        if (Admin::user()->isAdministrator()) {
            $this->select('application_id', '所属应用')
                ->required()
                ->options(Application::ofEnabled()->pluck('name', 'id'));
        }
        $this->radio('source', '域名来源')
            ->required()
            ->options(DomainSource::SOURCE_MAP)
            ->default(DomainSource::ALIYUN->value)
            ->when(DomainSource::CUSTOM->value, function ($form) {
                $form->text('domain', '域名地址')
                    ->help('活码域名一定要使用泛解析 *. 开始的记录，A记录请解析到IP: '.config('custom.slb_server_ip'))
                    ->rules('required_if:source,'.DomainSource::CUSTOM->value, [
                        'required_if' => '域名地址必须填写，且必须是泛解析',
                    ]);
            })
            ->when(DomainSource::ALIYUN->value, function ($form) {
                $form->select('aliyun_id', '云账户')
                    ->rules('required_if:source,'.DomainSource::ALIYUN->value)
                    ->options(Aliyun::ofAdmin()->pluck('name', 'id'))
                    ->load('root', route('admin.pools.domains'));
                $form->select('root', '根域名')
                    ->rules('required_if:source,'.DomainSource::ALIYUN->value);
                $form->text('rr', 'A记录')
                    ->prepend('*.')
                    ->help('泛解析记录，系统自动添加 "*." 前缀')
                    ->rules('required_if:source,'.DomainSource::ALIYUN->value);
            });
        $this->switch('status')
            ->default(true);
        $this->switch('ssl', '开启SSL')
            ->help('SSL可以有效防止DNS污染拦截，开通SSL需要提供SSL证书，联系管理员单独配置')
            ->readOnly();
    }
}
